﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NhJump.Persistence.Querying;
using NHibernate;

namespace NhJump.Persistence.Batching
{
    /// <summary>
    /// Executes a list of Criteria in a batch, and calls back to each resultAction with the result
    /// </summary>
    public class Batcher : IBatcher
    {
        private readonly IBatchExecuter _batchExecuter;
        private readonly IList<CriteriaWithResultAction> _contents = new List<CriteriaWithResultAction>();

        public Batcher(IBatchExecuter batchExecuter)
        {
            _batchExecuter = batchExecuter;
        }

        public void Add(ICriteria criteria, Action<IList> resultAction)
        {
            _contents.Add(new CriteriaWithResultAction(criteria, resultAction));
        }

        public void ExecuteAndClear()
        {
            IList results = _batchExecuter.Execute(_contents);

            for (int i = 0; i < _contents.Count; i++)
            {
                var queryActionTuple = _contents[i];

                queryActionTuple.ResultAction((IList)results[i]);
            }

            _contents.Clear();
        }

        public int Size
        {
            get
            {
                return _contents.Count;
            }
        }
    }
}
